

package com.kimo.shop.admin.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.kimo.shop.bean.event.ProdChangeStatusEvent;
import com.kimo.shop.bean.model.*;
import com.kimo.shop.bean.param.ProductExportParam;
import com.kimo.shop.bean.param.ProductParam;
import com.kimo.shop.bean.param.RetailProdParam;
import com.kimo.shop.common.exception.KimoShopBindException;
import com.kimo.shop.common.i18n.I18nMessage;
import com.kimo.shop.common.i18n.LanguageEnum;
import com.kimo.shop.common.util.Json;
import com.kimo.shop.common.util.PageParam;
import com.kimo.shop.delivery.comment.model.SameCity;
import com.kimo.shop.delivery.comment.service.SameCityService;
import com.kimo.shop.security.admin.util.SecurityUtils;
import com.kimo.shop.service.*;
import io.swagger.annotations.ApiOperation;
import ma.glasnost.orika.MapperFacade;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.Date;
import java.util.List;
import java.util.Objects;


/**
 * 商品列表、商品发布controller
 *
 * @author kimo-taozhouchuan
 */
@Controller
@RequestMapping("/prod/prod")
public class ProductController {

    @Autowired
    private ProductService productService;

    @Autowired
    private MapperFacade mapperFacade;

    @Autowired
    private SkuService skuService;

    @Autowired
    private ProdTagReferenceService prodTagReferenceService;

    @Autowired
    private ProdLangService prodLangService;

    @Autowired
    private BasketService basketService;

    @Autowired
    private ApplicationContext applicationContext;

    @Autowired
    private RetailProdService retailProdService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private ShopDetailService shopDetailService;

    @Autowired
    private SameCityService sameCityService;

    /**
     * 分页获取商品信息
     */
    @GetMapping("/page")
    @PreAuthorize("@pms.hasPermission('prod:prod:page')")
    public ResponseEntity<IPage<Product>> page(ProductParam product, PageParam<Product> page) {
//        IPage<Product> products = productService.page(page,
//                new LambdaQueryWrapper<Product>()
//                        .like(StrUtil.isNotBlank(product.getProdName()), Product::getProdName, product.getProdName())
//                        .eq(Product::getShopId, SecurityUtils.getSysUser().getShopId())
//                        .eq(product.getStatus() != null, Product::getStatus, product.getStatus())
//                        .eq(product.getCategoryId() != null, Product::getCategoryId, product.getCategoryId())
//                        .eq(Product::getProdType,0)
//                        .ne(Product::getStatus, -1)
//                        .orderByDesc(Product::getStatus)
//                        .orderByDesc(Product::getPutawayTime));
        product.setLang(I18nMessage.getDbLang());
        product.setShopId(SecurityUtils.getSysUser().getShopId());
        IPage<Product> products = productService.pageByLang(page,product);
        return ResponseEntity.ok(products);
    }


    /**
     * 获取信息
     */
    @GetMapping("/info/{prodId}")
    @PreAuthorize("@pms.hasPermission('prod:prod:info')")
    public ResponseEntity<Product> info(@PathVariable("prodId") Long prodId) {
        Product prod = productService.getProductByProdId(prodId, I18nMessage.getDbLang());
        if (!Objects.equals(prod.getShopId(), SecurityUtils.getSysUser().getShopId())) {
            // 没有权限获取该商品规格信息
            throw new KimoShopBindException("kimo.product.no.auth");
        }
        List<Sku> skuList = skuService.listByProdId(prodId, I18nMessage.getDbLang());
        for (Sku sku : skuList) {
            for (SkuLang skuLang : sku.getSkuLangList()) {
                // sku 规格国际化，因为不是关联表的形式，所以多语言一起返回数据
                if(Objects.equals(skuLang.getLang(),1)){
                    String propertiesEn = skuLang.getProperties();
                    sku.setPropertiesEn(StrUtil.isNotBlank(propertiesEn)?propertiesEn:sku.getProperties());
                    String skuName = skuLang.getSkuName();
                    sku.setSkuNameEn(StrUtil.isNotBlank(skuName)?skuName:sku.getSkuName());
                }
                // 适配一些数据
                if (StrUtil.isBlank(sku.getPropertiesEn())) {
                    sku.setPropertiesEn(sku.getProperties());
                }
            }
        }
        prod.setSkuList(skuList);

        //获取分组标签
        List<Long> listTagId = prodTagReferenceService.listTagIdByProdId(prodId);
        prod.setTagList(listTagId);
        // 获取语言列表
        List<ProdLang> prodLangList = prodLangService.list(new LambdaQueryWrapper<ProdLang>().eq(ProdLang::getProdId, prodId));
        prod.setProdLangList(prodLangList);
        // 是否是组合商品
        if (Objects.equals(1,prod.getIsCompose())) {
            for (Sku sku : skuList) {
                List<RetailProdParam> skuSingleProds = retailProdService.getBySkuId(sku.getSkuId());
                if (CollectionUtils.isNotEmpty(skuSingleProds)) {
                    sku.setSkuSingleProds(skuSingleProds);
                }
            }
        }
        return ResponseEntity.ok(prod);
    }

    /**
     * 保存
     */
    @PostMapping
    @PreAuthorize("@pms.hasPermission('prod:prod:save')")
    public ResponseEntity<String> save(@Valid @RequestBody ProductParam productParam) {
        checkParam(productParam);
        skuService.checkPartyCode(productParam.getSkuList(),false);
        Product product = mapperFacade.map(productParam, Product.class);
        product.setStatus(1);
        product.setDeliveryMode(Json.toJsonString(productParam.getDeliveryModeVo()));
        product.setShopId(SecurityUtils.getSysUser().getShopId());
        product.setUpdateTime(new Date());
        product.setPutawayTime(new Date());
        product.setCreateTime(new Date());
        product.setSoldNum(0);
        product.setWaterSoldNum(productParam.getWaterSoldNum());
        product.setVersion(0);
        product.setProdType(0);
        product.setGroupActivityId(0L);
        product.setSeckillActivityId(0L);
        productService.saveProduct(product,productParam);
        return ResponseEntity.ok().build();
    }

    /**
     * 修改
     */
    @PutMapping
    @PreAuthorize("@pms.hasPermission('prod:prod:update')")
    public ResponseEntity<String> update(@Valid @RequestBody ProductParam productParam) {
        checkParam(productParam);
        skuService.checkPartyCode(productParam.getSkuList(),true);
        Product dbProduct = productService.getProductByProdId(productParam.getProdId(), I18nMessage.getDbLang());
        if (!Objects.equals(dbProduct.getShopId(), SecurityUtils.getSysUser().getShopId())) {
            // 无法获取非本店铺商品信息
            throw new KimoShopBindException("kimo.product.not.exist");
        }
        // 先查询需要删除的用户购物车缓存
        List<String> userIds = basketService.listUserIdByProdId(dbProduct.getProdId());

        List<Sku> dbSkus = skuService.listByProdId(dbProduct.getProdId(), I18nMessage.getDbLang());


        Product product = mapperFacade.map(productParam, Product.class);
        product.setDeliveryMode(Json.toJsonString(productParam.getDeliveryModeVo()));
        product.setUpdateTime(new Date());

        dbProduct.setSkuList(dbSkus);
        productParam.setProdType(null);
        productService.updateProduct(productParam, dbProduct);

        //清除缓存
        productService.removeProdCacheByProdId(productParam.getProdId(), LanguageEnum.LANGUAGE_EN.getLang());
        productService.removeProdCacheByProdId(productParam.getProdId(),LanguageEnum.LANGUAGE_ZH_CN.getLang());
        for (String userId : userIds) {
            basketService.removeShopCartItemsCacheByUserId(userId, LanguageEnum.LANGUAGE_ZH_CN.getLang());
            basketService.removeShopCartItemsCacheByUserId(userId, LanguageEnum.LANGUAGE_EN.getLang());
        }
        for (Sku sku : dbSkus) {
            skuService.removeSkuCacheBySkuId(sku.getSkuId(), sku.getProdId(), LanguageEnum.LANGUAGE_ZH_CN.getLang());
            skuService.removeSkuCacheBySkuId(sku.getSkuId(), sku.getProdId(), LanguageEnum.LANGUAGE_EN.getLang());
        }
        return ResponseEntity.ok().build();
    }

    /**
     * 删除
     */
    @DeleteMapping("/{prodId}")
    @PreAuthorize("@pms.hasPermission('prod:prod:delete')")
    public ResponseEntity<Void> delete(@PathVariable("prodId") Long prodId) {
        Product dbProduct = productService.getProductByProdId(prodId, I18nMessage.getDbLang());
        if (!Objects.equals(dbProduct.getShopId(), SecurityUtils.getSysUser().getShopId())) {
            // 无法获取非本店铺商品信息
            throw new KimoShopBindException("kimo.product.not.exist");
        }
        List<Sku> dbSkus = skuService.listByProdId(dbProduct.getProdId(), I18nMessage.getDbLang());
//        if (Objects.equals(1,dbProduct.getIsCompose())) {
//            // 如果是组合商品就，删除关联单品
//            skuRetailMapper.deleteByProdId(dbProduct.getProdId());
//        }
        // 删除商品
        productService.removeProductByProdId(prodId);

        //清除商品缓存
        productService.removeProdCacheByProdId(prodId, LanguageEnum.LANGUAGE_EN.getLang());
        productService.removeProdCacheByProdId(prodId,LanguageEnum.LANGUAGE_ZH_CN.getLang());

        //清除sku缓存
        for (Sku sku : dbSkus) {
            skuService.removeSkuCacheBySkuId(sku.getSkuId(), sku.getProdId(), LanguageEnum.LANGUAGE_ZH_CN.getLang());
            skuService.removeSkuCacheBySkuId(sku.getSkuId(), sku.getProdId(), LanguageEnum.LANGUAGE_EN.getLang());
        }

        List<String> userIds = basketService.listUserIdByProdId(prodId);
        //清除购物车缓存
        for (String userId : userIds) {
            basketService.removeShopCartItemsCacheByUserId(userId, LanguageEnum.LANGUAGE_ZH_CN.getLang());
            basketService.removeShopCartItemsCacheByUserId(userId, LanguageEnum.LANGUAGE_EN.getLang());
        }

        return ResponseEntity.ok().build();
    }
    /**
     * 更新注水销量
     */
    @PutMapping("/waterSoldNum")
    public ResponseEntity<Void> updateWaterSoldNum(Integer waterSoldNum,Long prodId){
        if (waterSoldNum == null){
            waterSoldNum = 0;
        }
        productService.updateWaterSoldNum(waterSoldNum, prodId);
        return ResponseEntity.ok().build();
    }

    /**
     * 更新商品状态
     */
    @PutMapping("/prodStatus")
    public ResponseEntity<Void> prodStatus(@RequestBody ProductParam productParam) {
        Long prodId = productParam.getProdId();
        Integer prodStatus = productParam.getStatus();
        Product dbProduct = productService.getProductByProdId(prodId, I18nMessage.getDbLang());
        if (Objects.equals(productParam.getStatus(), 1)) {
            Category category = categoryService.getById(dbProduct.getCategoryId());
            if (!Objects.equals(category.getStatus(), 1)) {
                // 分类处于下线中，商品不能上架
                throw new KimoShopBindException("kimo.product.category.offline");
            }
        }

        if (!Objects.equals(dbProduct.getShopId(), SecurityUtils.getSysUser().getShopId())) {
            // 无法获取非本店铺商品信息
            throw new KimoShopBindException("kimo.product.not.exist");
        }

        Product product = new Product();
        product.setProdId(prodId);
        product.setStatus(prodStatus);
        if (prodStatus == 1) {
            product.setPutawayTime(new Date());
        }
        dbProduct.setStatus(prodStatus);
        // 商品状态改变时的发送事件，让活动下线
        applicationContext.publishEvent(new ProdChangeStatusEvent(dbProduct,dbProduct.getStatus()));

        productService.updateById(product);

        // 如果是商品下架操作
        // 此段代码可以用Spring事件监听进行解耦，时间紧迫，以后再算，有待优化。

        productService.removeProdCacheByProdId(prodId, LanguageEnum.LANGUAGE_EN.getLang());
        productService.removeProdCacheByProdId(prodId,LanguageEnum.LANGUAGE_ZH_CN.getLang());
        List<String> userIds = basketService.listUserIdByProdId(prodId);

        for (String userId : userIds) {
            basketService.removeShopCartItemsCacheByUserId(userId, LanguageEnum.LANGUAGE_ZH_CN.getLang());
        }
        return ResponseEntity.ok().build();
    }

    /**
     * 批量删除
     * @param ids
     * @return 是否删除成功
     */
    @DeleteMapping
    public ResponseEntity<Boolean> batchRemoveById(@RequestBody Long[] ids) {
        // TODO 待优化
        StringBuilder stringBuilder = new StringBuilder();
        for (Long prodId : ids) {
            try {
                delete(prodId);
            } catch (Exception e) {
                Product dbProduct = productService.getProductByProdId(prodId, I18nMessage.getDbLang());
                stringBuilder.append("【").append(dbProduct.getProdName()).append("】  ");

            }
        }
        if (stringBuilder.length()>0){
            throw new KimoShopBindException("部分商品删除异常，请刷新页面后手动检查：" + stringBuilder.toString());
        }
        return ResponseEntity.ok().build();
    }

    /**
     * 批量更新商品状态
     * @param ids
     * @param status
     * @return
     */
    @PutMapping("/batchProdStatus/{status}")
    public ResponseEntity<Void> batchShopStatus(@RequestBody Long[] ids, @PathVariable("status") Integer status) {
        // TODO 待优化
        ProductParam product = new ProductParam();
        product.setStatus(status);
        StringBuilder stringBuilder = new StringBuilder();
        for (Long prodId : ids) {
            product.setProdId(prodId);
            try {
                prodStatus(product);
            } catch (Exception e) {
                Product dbProduct = productService.getProductByProdId(prodId, I18nMessage.getDbLang());
                //【商品名】:错误信息xxx (【数码相机】:本店分类处于下线中，商品不能上架)
                //stringBuffer.append("【"+dbProduct.getProdName()+"】:"+e.getMessage()+"\n");
                stringBuilder.append("【").append(dbProduct.getProdName()).append("】  ");
            }
        }
        if (stringBuilder.length()>0){
            throw new KimoShopBindException("修改成功！部分商品状态修改异常，请刷新页面后手动检查：" + stringBuilder.toString());
        }
        return ResponseEntity.ok().build();
    }

    /**
     * 导出商品
     *
     * @param productParam 导出商品筛选条件
     */
    @GetMapping("/exportProd")
    public void exportProd(ProductExportParam productParam, HttpServletResponse response) {
        Long shopId = SecurityUtils.getSysUser().getShopId();
        productParam.setShopId(shopId);
//        productParam.setStatus(productParam.getStatus() == null ? ProdStatusEnums.NORMAL.getValue():productParam.getStatus());
        productService.exportProd(productParam,response,shopId);
    }

    @GetMapping(value = "/downloadModel")
    public void downloadModel(HttpServletResponse response) {
        productService.downloadModel(response,SecurityUtils.getSysUser().getShopId());
    }


    @ApiOperation(value = "导入文件")
    @RequestMapping(value = "/exportExcel", method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity exportExcel(@RequestParam("excelFile") MultipartFile excelFile) throws Exception {
        if(excelFile == null) {
            // 网络繁忙，请稍后重试
            throw new KimoShopBindException("kimo.network.busy");
        }
        Long shopId = SecurityUtils.getSysUser().getShopId();
        SameCity sameCity = sameCityService.getSameCityByShopId(shopId);
        // 是否开启同城配送
        boolean isSameCity = true;
        if (Objects.isNull(sameCity) || !Objects.equals(1, sameCity.getStatus())) {
            isSameCity = false;
        }
        return ResponseEntity.ok(productService.parseFile(excelFile,shopId,isSameCity));
    }


    private void checkParam(ProductParam productParam) {
        if (CollectionUtil.isEmpty(productParam.getTagList())) {
            // 请选择产品分组
            throw new KimoShopBindException("kimo.prod.group.check");
        }

        Product.DeliveryModeVO deliveryMode = productParam.getDeliveryModeVo();
        boolean hasDeliverMode = deliveryMode != null
                && (deliveryMode.getHasShopDelivery() || deliveryMode.getHasUserPickUp());
        if (!hasDeliverMode) {
            // 请选择配送方式
            throw new KimoShopBindException("kimo.product.dvy.type");
        }
        if (Objects.equals(productParam.getPreSellStatus(),1) && Objects.nonNull(productParam.getPreSellTime())
                && DateUtil.compare(productParam.getPreSellTime(),new Date()) < 0) {
            // 预售时间不能小于当前时间
            throw new KimoShopBindException("kimo.product.preSellTime.check");
        }
        List<Sku> skuList = productParam.getSkuList();
        boolean isAllUnUse = true;
        for (Sku sku : skuList) {
            if (sku.getStatus() == 1) {
                isAllUnUse = false;
            }
        }
        if (isAllUnUse) {
            // 至少要启用一种商品规格
            throw new KimoShopBindException("kimo.product.enable.sku");
        }
        if (Objects.equals(1,productParam.getIsCompose())) {
            // 如果是组合商品，必须又一个sku是与单品关联的
            productParam.getSkuList().forEach(i->
                    {
                        if (CollectionUtils.isEmpty(i.getSkuSingleProds())) {
                            // 组合单品必须关联一个单品
                            throw new KimoShopBindException("kimo.product.group.check");
                        }
                        for (RetailProdParam skuSingleProd : i.getSkuSingleProds()) {
                            if (skuSingleProd.getRetailNums() <= 0) {
                                throw new KimoShopBindException(i.getSkuName() + skuSingleProd.getName() + I18nMessage.getMessage("kimo.retail.prod.compose"));
                            }
                        }
                    }
            );
        }
    }
}
